/**
 *
 */
package com.wedroid.r2d2.message.command;

import java.util.Collections;
import java.util.Map;

import org.hashids.Hashids;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.demo2do.core.utils.StringUtils;
import com.wedroid.entity.Constant;
import com.wedroid.entity.command.Command;
import com.wedroid.entity.contact.Contacter;
import com.wedroid.entity.contact.Droid;
import com.wedroid.r2d2.cache.PersistentAccessor;
import com.wedroid.r2d2.contact.Contact;
import com.wedroid.r2d2.message.RipeMessage;

/**
 * @author lute
 */
public abstract class TemplateCommandOperator implements CommandOperator {

    private static final Hashids hashids = new Hashids(Constant.HASHIDS_SALT, Constant.HASHIDS_MIN_LENGTH);

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PersistentAccessor accessor;

    /* (non-Javadoc)
     * @see com.wedroid.r2d2.message.command.CommandOperator#operate(com.wedroid.entity.command.Command, com.wedroid.r2d2.message.RipeMessage)
     */
    public void operate(Command command, RipeMessage originalMessage) {
        Contact droidContact = originalMessage.getDroid();
        Contact sender = originalMessage.getSender();

        String template = command.getTemplate();
        if (StringUtils.hasPlaceHolder(template)) {
            Droid droid = accessor.getDroid(droidContact.getNickName());
            Contacter contacter = accessor.getContacter(droid, sender.getNickName());

            Map<String, String> values = Collections.singletonMap("contacterIdentifier", hashids.encode(contacter.getId()));
            template = StringUtils.replacePlaceHolder(template, values);
        }

        doOperate(command, template, sender);
    }

    /**
     * @param template
     * @param sender
     */
    protected abstract void doOperate(Command command, String template, Contact sender);

}
